package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     *  查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //校验参数
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查分页参数
        dto.checkParam();
        //2.执行分页条件查询
        //2.1分页条件对象
        Page<ApUserRealname> page = new Page<ApUserRealname>(dto.getPage(),dto.getSize());
        //查询条件
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        //判断状态
        if(dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //查询数据
        IPage<ApUserRealname> resultPage = page(page, wrapper);
        //返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal(), resultPage.getRecords());

        return result;
    }

    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;
    /**
     * 根据状态进行审核
     * @param dto
     * @param status    2 审核失败   9 审核成功
     * @return
     */
    //开启事务
    @GlobalTransactional(rollbackFor = Exception.class)
    //@Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1 参数检查
        if(dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id为空");
        }
        //2 根据id查询当前认证用户
        ApUserRealname  apUserRealname= this.getById(dto.getId());
        if(apUserRealname==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的实名认证信息不存在");
        }
        //判断认证状态是否为待审核
        if(!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证状态不是待审核状态");
        }
        //查询用户信息所关联的opUser账户
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
            //判断用户信息是否存在
        if(apUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联opUser账户不存在");
        }
        //3 更新认证用户信息
        apUserRealname.setStatus(status);//更改状态
        apUserRealname.setUpdatedTime(new Date());//更新修改时间
        //判断是否存在未通过的原因
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        this.updateById(apUserRealname);
        //判断状态是否为9
        if(AdminConstants.PASS_AUTH.equals(status)){
            //创建自媒体账户
            WmUser wmUser = createWmUser(apUser);
            //创建作者信息
            createApAuthor(wmUser);
        }
        return ResponseResult.okResult();
    }

    /**
     * 远程调用自媒体服务，创建自媒体账户
     * @param apUser       APP端用户
     * @return
     */
    public WmUser createWmUser(ApUser apUser){
        //远程调用查询,判断自媒体账户是否存在
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()) {
            //远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        //判断账户是否存在
        if(wmUser!=null){
            //存在抛异常
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体账户已存在");
        }
        //不存在
        wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setApUserId(apUser.getId());
//        wmUser.setName(apUser.getName());
//        wmUser.setPassword(apUser.getPassword());
//        wmUser.setSalt(apUser.getSalt());
//        wmUser.setImage(apUser.getImage());
//        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        //远程保存自媒体账户
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(!saveResult.checkCode()){
            //远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return saveResult.getData();
    }

    /**
     * 远程创建作者信息
     * @param wmUser
     */
    public void createApAuthor(WmUser wmUser){
        //远程查询，判断作者信息是否存在
        ResponseResult<ApAuthor> authorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if(!authorResult.checkCode()){
            //远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApAuthor apAuthor = authorResult.getData();
        //判断作者信息是否存在
        if(apAuthor!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已存在");
        }
        //如果不存在，创建
        apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        //远程保存作者信息
        ResponseResult result = articleFeign.save(apAuthor);
        if(!result.checkCode()){
            //远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }
}
